'use strict';

const await = require('await-stream-ready/lib/await');

const Controller = require('egg').Controller;

class ScoreController extends Controller {
    // 列表
    async index() {
        const { ctx, app } = this;
        let { username, class_id, branch_id, exam_id } = ctx.query;
        class_id = class_id ? parseInt(class_id) : ''
        exam_id = exam_id ? parseInt(exam_id) : ''
        branch_id = branch_id ? parseInt(branch_id) : ''
        let where = {};

        if (username) {
            let user = await app.model.User.findOne({
                where: {
                    username
                }
            })
            where.user_id = user.id;
        }
        if (class_id) {
            where.class_id = class_id;
        }
        if (exam_id) {
            where.exam_id = exam_id;
        }
        if (branch_id) {
            where.branch_id = branch_id;
        }
        // 查询学生分数信息
        let data = await app.model.Score.findAll({
            where,
            include: [
                {
                    model: app.model.User,
                    as: 'user',
                },
                {
                    model: app.model.Class,
                    as: 'class',
                },
                {
                    model: app.model.Branch,
                    as: 'branch',
                },
                {
                    model: app.model.Exam,
                    as: 'exam',
                },
            ],
        });
        // ctx.body = data
        data = JSON.parse(JSON.stringify(data))
        let brancho = await app.model.Branch.findAll()
        brancho = JSON.parse(JSON.stringify(brancho))
        let classo = await app.model.Class.findAll()
        classo = JSON.parse(JSON.stringify(classo))
        await ctx.renderTemplate({
            title: "成绩列表",
            tempType: "table",
            table: {
                // 按钮
                buttons: {
                    // 新增操作
                    add: "/admin/score/create"
                },
                // 搜索
                search: {
                    // 提交地址
                    action: "/admin/score",
                    // 字段配置
                    fields: [{
                        label: "姓名",
                        type: "text",
                        name: "username",
                        placeholder: "请输入姓名或ID"
                    }, {
                        label: "所在班级",
                        type: "select",
                        name: "class_id",
                        field: "name",
                        options: classo,
                        placeholder: "所在班级"
                    }, {
                        label: "学科",
                        type: "select",
                        name: "branch_id",
                        field: "name",
                        options: brancho,
                        placeholder: "学科"
                    },]
                },
                // 表头
                columns: [{
                    title: "ID",
                    fixed: 'center',
                    key: "id"
                }, {
                    title: "姓名",
                    fixed: 'left',
                    render(item) {
                        return `
                        <h2>
                            <a href="">${item.user.username}</a>
                        </h2>
                        `
                    }
                }, {
                    title: "学科",
                    fixed: 'center',
                    render(item) {
                        return `
                        <h2>
                            ${item.branch.name}
                        </h2>
                        `
                    }
                }, {
                    title: "分数",
                    fixed: 'center',
                    key: "score"
                }, {
                    title: "创建时间",
                    fixed: 'center',
                    width: 180,
                    key: "created_time"
                }, {
                    title: "操作",
                    width: 200,
                    fixed: 'center',
                    action: {
                        edit: function (id) {
                            return `/admin/score/edit/${id}`
                        },
                        delete: function (id) {
                            return `/admin/score/delete/${id}`
                        },
                    }
                }]
            },
            data
        })
    }


    // 创建表单
    async create() {
        const { ctx, app } = this;
        const id = ctx.params.id
        let exam = await app.model.Exam.findOne({
            where: {
                id
            }
        })
        exam = JSON.parse(JSON.stringify(exam))
        let usero = await app.model.User.findAll({
            where: {
                class_id: exam.class_id
            }
        })
        usero = JSON.parse(JSON.stringify(usero))
        usero.map((item, index) => {
            item.index = index;
            return item;
        })
        let brancho = await app.model.Branch.findAll()
        brancho = JSON.parse(JSON.stringify(brancho))
        await ctx.renderTemplate({
            // 页面标题
            title: "录入成绩",
            // 模板类型 form表单，table表格分页
            tempType: "form",
            // 表单配置
            form: {
                // 提交地址
                action: "/admin/score",
                // 字段配置
                fields: [{
                    label: "学科",
                    type: "select",
                    name: "branch_id",
                    field: "name",
                    options: brancho,
                    placeholder: "学科"
                }, {
                    label: "成绩",
                    type: "score",
                    name: "user_id",
                    field: "username",
                    options: usero,
                    placeholder: "学生姓名"
                }],
                exam,
            },
            // 是否显示完成按钮
            completeBtn: true,
            // 新增成功跳转路径
            successUrl: "/admin/score"
        });
    }

    // 创建逻辑
    async save() {
        const { ctx, app } = this;
        ctx.validate({
            branch_id: {
                type: "int",
                required: true,
                desc: "学科"
            },
            class_id: {
                type: "int",
                required: true,
                desc: "班级id"
            },
            exam_id: {
                type: "int",
                required: true,
                desc: "成绩单id"
            },
            scores: {
                type: "array",
                required: true,
                desc: "成绩"
            },
            images: {
                type: "array",
                required: true,
                desc: "附件"
            },

        })
        let { branch_id, class_id, exam_id, scores, images, complete } = ctx.request.body;
        console.log(images)
        console.log(scores)
        let usero = await app.model.User.findAll({
            where: {
                class_id: class_id
            }
        })
        usero = JSON.parse(JSON.stringify(usero))
         // 检查该成绩单的成绩是否录入
         if(scores.length !== usero.length ){
            return ctx.apiFail('请完成学生成绩录入后再提交');
        }

        // 检查该成绩单下是否已经存在同科的成绩
        let score = await app.model.Score.findAll({
            where: {
                class_id: class_id,
                exam_id: exam_id,
                branch_id: branch_id
            }
        })
        if (score.length != 0) {
            return ctx.apiFail('该科目成绩已存在，请勿重复录入');
        }
        let data = {}
        
        for (const item of usero) {
            const index = usero.indexOf(item);
            data.user_id = usero[index].id;
            data.exam_id = exam_id;
            data.class_id = class_id;
            data.branch_id = branch_id;
            data.score = scores[index];
            data.image = images[index];
            data.status = 1;
            let res = await this.app.model.Score.create(data);
        }
        // 更改成绩单状态为"已录入"
        let exam = await app.model.Exam.findOne({
            where: {
                id: exam_id
            }
        })
        if (exam && complete) {
            exam.status = 2  //已完成
        }else{
            exam.status = 1  //已录入
        }
        await exam.save()



    }

    // 编辑表单页
    async edit() {
        const { ctx, app } = this
        const id = ctx.params.id
        const usero = await app.model.User.findAll()
        const brancho = await app.model.Branch.findAll()

        let data = await app.model.Score.findOne({
            where: {
                id
            }
        })
        if (!data) {
            return await ctx.pageFail('该记录不存在')
        }

        data = JSON.parse(JSON.stringify(data))

        await ctx.renderTemplate({
            id,
            title: "修改成绩",
            tempType: "form",
            form: {
                // 提交地址
                action: "/admin/score/" + id,
                // 字段配置
                fields: [{
                    label: "学生姓名",
                    type: "select",
                    name: "user_id",
                    field: "username",
                    options: usero,
                    placeholder: "学生姓名"
                }, {
                    label: "学科",
                    type: "select",
                    name: "branch_id",
                    field: "name",
                    options: brancho,
                    placeholder: "学科"
                }, {
                    label: "分数",
                    type: "float",
                    name: "score",
                    placeholder: "分数"
                }, {
                    label: "点评",
                    type: "string",
                    name: "comment",
                    placeholder: "点评"
                }],
                // 默认值
                data
            },
            // 修改成功跳转路径
            successUrl: "/admin/score"
        })
    }

    // 更新逻辑
    async update() {
        const { ctx, app } = this;
        ctx.validate({
            id: {
                type: "int",
                required: true
            },
            user_id: {
                type: "int",
                required: true,
                desc: "学生姓名"
            },
            branch_id: {
                type: "int",
                required: true,
                desc: "学科"
            },
            score: {
                type: "float",
                required: true,
                desc: "分数"
            },
            comment: {
                type: "string",
                required: false,
                desc: "点评"
            },
        })

        let id = ctx.params.id
        let { user_id, branch_id, score, comment } = ctx.request.body

        let scores = await app.model.Score.findOne({
            where: {
                id
            }
        })
        if (!scores) {
            return ctx.apiFail('该记录不存在')
        }

        scores.user_id = user_id
        scores.branch_id = branch_id
        scores.score = score
        scores.comment = comment

        ctx.apiSuccess(await scores.save())

    }

    // 删除
    async delete() {
        const { ctx, app } = this;
        const id = ctx.params.id
        await app.model.Score.destroy({
            where: {
                id
            }
        })
        ctx.toast('删除成功', 'success')
        ctx.redirect('/admin/score')
    }
}

module.exports = ScoreController;
